<?php
namespace app\wechat\controller;
use think\Controller;
use think\Session;
use think\Config;
use app\model\Users;
use EasyWeChat\Factory;

class AuthController extends Controller
{
    protected $app;
    protected $openid;
    protected $user_id;
    protected $user_info;

    protected function _initialize()
    {
        $this->app = Factory::officialAccount(Config::get('wechat'));
    }

    public function login(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $user = Users::get([
                'nickname'=>$data['nickname'],
                'password'=>$data['password']
            ]);
            if($user){
                $session_data = [
                    'nickname' => $user['nickname'],
                    'sex' => $user['sex'],
                    'status' => $user['status'],
                ];
                Session::set('user_info', $session_data);
                Session::set('user_id', $user['id']);
                Session::set('openid', '');
                return msgReturn(true,'登录成功');
            }else{
                return msgReturn(false,'用户名或密码错误');
            }
        }else{
            return $this->fetch();
        }
    }

    public function reg(){
        if($this->request->isPost()){
            $data = $this->request->post();
            if(Users::get(['nickname'=>$data['nickname']])){
                return msgReturn(false,'用户名已存在');
            }else{
                $user_data = [
                    'openid' => '',
                    'nickname' => $data['nickname'],
                    'password' => $data['password'],
                    'sex' => 1,
                    'headpic' => '/assets/wechat/images/wd_t.png',
                ];
                $this->wechatReg($user_data);
                return msgReturn(true,'注册成功');
            }
        }else{
            return $this->fetch();
        }
    }

    /**
     * 微信授权登录
     * @return bool
     */
    public function wechatLogin()
    {
        $this->user_id = Session::get('user_id');
        $this->openid = Session::get('openid');
        $this->user_info = Session::get('user_info');
        if ((!$this->user_id) || (!$this->openid) || (!$this->user_info)) {
            $response = $this->app->oauth->scopes(['snsapi_userinfo'])->redirect();
            $response->send();
        }else{
            $this->redirect('wechat\Index\index');
        }
    }

    /**
     * 授权回调页面
     * @throws \think\exception\DbException
     */
    public function oauthCallBack(){
        $oauth = $this->app->oauth;
        try {
            // 获取 OAuth 授权结果用户信息
            $user = $oauth->user();
        } catch(\Exception $e){
            return $e->getMessage();
        }

        $this->openid = $user->getId();
        $user_info = Users::get(['openid' => $this->openid]);
        if ($user_info) {
            $session_data = [
                'nickname' => $user_info['nickname'],
                'sex' => $user_info['sex'],
                'status' => $user_info['status'],
            ];
            Session::set('user_info', $session_data);
            Session::set('user_id', $user_info['id']);
            Session::set('openid', $this->openid);
            //更新最新信息
            $origin = $user->getOriginal();
            $user_data = [
                'nickname' => $user->getNickName(),
                'sex' => $origin['sex'],
                'headpic' => $user->getAvatar(),
            ];
            $user_info->data($user_data);
            $user_info->save();
        } else {
            $origin = $user->getOriginal();
            $user_data = [
                'openid' => $user->getId(),
                'nickname' => $user->getNickName(),
                'sex' => $origin['sex'],
                'headpic' => $user->getAvatar(),
            ];
            $this->wechatReg($user_data);
        }
        $this->redirect('wechat\Index\index');
    }

    /**
     * 注册用户
     * @param null $data
     * @return bool
     */
    public function wechatReg($user_info)
    {
        $user = new Users();
        $user->data($user_info);
        $user->save();
        $new_user = Users::get(['id'=>$user->id]);

        $session_data = [
            'nickname' => $new_user['nickname'],
            'sex' => $new_user['sex'],
            'status' => $new_user['status'],
        ];

        Session::set('user_info', $session_data);
        Session::set('user_id', $user->id);
        Session::set('openid', $user_info['openid']);
        return true;
    }

    /**
     * 用户同意协议
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function agree(){
        if($this->request->param('agree')){
            $user = Users::get(['id'=>Session::get('user_id')]);
            $user->status = 1;
            $user->save();

            $new_user = Users::get(['id'=>$user->id]);
            $session_data = [
                'nickname' => $new_user['nickname'],
                'sex' => $new_user['sex'],
                'status' => $new_user['status'],
            ];

            Session::set('user_info', $session_data);

            $this->success('用户已经同意该协议，请遵守相关法律法规','wechat/Index/index');
        }else{
            return $this->fetch();
        }
    }
}
